package com.example.victory.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.victory.config.Const;
import com.example.victory.entity.companyEntity.NewSharestockEntity;
import com.example.victory.mapper.CustomerMapper;
import com.example.victory.service.fsdp.FsdpUtilService;
import com.example.victory.swagger.handler.MiniAppNewSharestockApiDelegate;
import com.example.victory.swagger.model.*;
import com.example.victory.utils.AnalysisUtils;
import com.example.victory.utils.CrmUtils;
import com.cgws.fintech.sdk.api.inner.security.model.User;
import com.cgws.fintech.sdk.api.mvp.model.ApiRequestCustomerQueryData;
import com.cgws.fintech.sdk.api.mvp.model.CustomerAccount;
import com.cgws.fintech.sdk.common.utils.DateHelper;
import com.cgws.fintech.sdk.common.utils.MoneyHelper;
import com.example.victory.common.web.ServiceHelper;
import com.cgws.fintech.sdk.inner.utils.web.SessionService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class MiniAppNewSharestockService implements MiniAppNewSharestockApiDelegate {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private SessionService sessionService;
    @Autowired
    private MvpLoginService mvpLoginService;
    @Autowired
    private FsdpUtilService fsdpUtilService;

    /**
     * 获取上一个交易日
     * @return 上一个交易日
     */
    @Override
    public ResponseEntity<ApiResponseLastTradeDate> getLastTradeDate() {
        String lastTradeDate = customerMapper.getTradingDateYYYY_MM_DD(Integer.valueOf(DateHelper.getDateYYYYMMDD(new Date())),1);
        ApiResponseLastTradeDateData apiResponseLastTradeDateData = new ApiResponseLastTradeDateData();
        apiResponseLastTradeDateData.setLastTradeDate(lastTradeDate);
        return ResponseEntity.ok(new ApiResponseLastTradeDate().data(apiResponseLastTradeDateData));
    }

    @Override
    public ResponseEntity<ApiResponseNewSharestock> getNewSharestock(ApiRequestNewSharestock param) {
        ApiRequestNewSharestockData data = param.getData();
        ServiceHelper.checkDataNotNull(data, "data");
        Integer index = data.getIndex();
        Integer pageSize = data.getPageSize();
        String searchKey = data.getSearchKey();
        Integer custLevelSearch = data.getCustLevelSearch();
        Integer relationTypeSearch = data.getRelationTypeSearch();
        String startDate = data.getStartDate();
        String endDate = data.getEndDate();

        if (index == null) index = 0; // 首页
        if (pageSize == null) pageSize = 20; // 默认20条

        String lastTradeDate = customerMapper.getTradingDateYYYY_MM_DD(Integer.valueOf(DateHelper.getDateYYYYMMDD(new Date())),1);
        if (startDate == null || endDate == null) { // 刚进入小程序默认不传该日期
            startDate = lastTradeDate;
            endDate = lastTradeDate;
        }
        startDate = startDate.replace("-", "");
        endDate = endDate.replace("-", "");

        ApiResponseNewSharestockData newSharestockData = new ApiResponseNewSharestockData();
        List<NewSharestockInfo> custInfoList = new ArrayList<>();
        List<ApiRequestCustomerQueryData> customerQueryDataList = Lists.newArrayList();

        // 获取当前用户
        User user = sessionService.getCurrentUserSession(true).getUser();
        String crmId = user.getCrmId();
        if (crmId == null) crmId = "";
//        if (crmId == null) crmId = "1082262";
        List<NewSharestockEntity> entityList = customerMapper.getNewSharestockInfo(crmId, searchKey, custLevelSearch,
                relationTypeSearch, startDate, endDate, index * pageSize, (index + 1) * pageSize);

        if (entityList == null || entityList.size() == 0) {
            newSharestockData.setItems(Collections.emptyList());
            return ResponseEntity.ok(new ApiResponseNewSharestock().data(newSharestockData));
        }

        entityList.forEach(entity -> {
            ApiRequestCustomerQueryData customerQueryData=new ApiRequestCustomerQueryData();
            customerQueryData.setCustNum(entity.getCustomerId());
            customerQueryDataList.add(customerQueryData);

            NewSharestockInfo newSharestockInfo = new NewSharestockInfo();
            newSharestockInfo.setWinDate(entity.getWinDate());
            newSharestockInfo.setName(entity.getName());
            newSharestockInfo.setPhone(entity.getPhone());
            newSharestockInfo.setCustomerId(entity.getCustomerId());
            newSharestockInfo.setRelationType(AnalysisUtils.getRelationType(entity.getRelationType()));
            newSharestockInfo.setCustLevel(entity.getCustLevel());

            ArrayList<KeyValueDetail> keyValueList = Lists.newArrayList();

            KeyValueDetail availableTotal = new KeyValueDetail();
            availableTotal.setName("资产余额");
            availableTotal.setValue(MoneyHelper.formatMoney(new BigDecimal(entity.getAvailableTotal().trim())));
            keyValueList.add(availableTotal);

            KeyValueDetail winAccount = new KeyValueDetail();
            winAccount.setName("中签账户");
            winAccount.setValue(entity.getWinAccount());
            keyValueList.add(winAccount);

            KeyValueDetail winCode = new KeyValueDetail();
            winCode.setName("中签代码");
            winCode.setValue(entity.getWinCode());
            keyValueList.add(winCode);

            KeyValueDetail winForShort = new KeyValueDetail();
            winForShort.setName("中签简称");
            winForShort.setValue(entity.getWinForShort().trim());
            keyValueList.add(winForShort);

            KeyValueDetail winAmount = new KeyValueDetail();
            winAmount.setName("中签金额");
            winAmount.setValue(MoneyHelper.formatMoney(new BigDecimal(entity.getWinCount() * entity.getSharestockAmount())));
            keyValueList.add(winAmount);

            KeyValueDetail winDate = new KeyValueDetail();
            winDate.setName("中签日期");
            winDate.setValue(entity.getWinDate().trim());
            keyValueList.add(winDate);

            newSharestockInfo.setDetails(keyValueList);
            custInfoList.add(newSharestockInfo);
        });

        if(customerQueryDataList.size()>0){
            List<CustomerAccount> customerAccountList = CrmUtils.getCustAccountListByIds(mvpLoginService, customerQueryDataList);
            if (customerAccountList != null) {
                custInfoList.forEach(customer -> {
                    customerAccountList.forEach(customerAccount->{
                        if(!StringUtils.isEmpty(customerAccount.getFcid())&&customer.getCustomerId().equals(customerAccount.getCustNum())){
                            customer.setImId(customerAccount.getFcid());
                        }
                    });
                });
            }
        }
        return ResponseEntity.ok(new ApiResponseNewSharestock().data(newSharestockData.items(custInfoList)));
    }

    @Override
    public ResponseEntity<ApiResponseListedSharestock> getListedSharestock(ApiRequestListedSharestock param) {
        ApiRequestListedSharestockData data = param.getData();
        ServiceHelper.checkDataNotNull(data, "data");
        Integer index = data.getIndex();
        Integer pageSize = data.getPageSize();
        String searchKey = data.getSearchKey();
        Integer relationTypeSearch = data.getRelationTypeSearch();
        String startDate = data.getStartDate();
        String endDate = data.getEndDate();

        if (index == null) index = 1; // 首页
        if (pageSize == null) pageSize = 20; // 默认20条

        String lastTradeDate = customerMapper.getTradingDateYYYY_MM_DD(Integer.valueOf(DateHelper.getDateYYYYMMDD(new Date())),1);
        if (startDate == null || endDate == null) { // 刚进入小程序默认不传该日期
            startDate = lastTradeDate;
            endDate = lastTradeDate;
        }
        startDate = startDate.replace("-", "");
        endDate = endDate.replace("-", "");

        ApiResponseListedSharestockData listedSharestockData = new ApiResponseListedSharestockData();
        List<ListedSharestockInfo> custInfoList = new ArrayList<>();
        List<ApiRequestCustomerQueryData> customerQueryDataList = Lists.newArrayList();

        // 获取当前用户
        User user = sessionService.getCurrentUserSession(true).getUser();
        String crmId = user.getCrmId();
        if (crmId == null) crmId = "";

        JSONObject fsdpParam = new JSONObject();
        fsdpParam.put("I_INDEX", index);
        fsdpParam.put("I_PAGESIZE", pageSize);
        fsdpParam.put("I_RYID", crmId);
        fsdpParam.put("I_KSRQ", startDate);
        fsdpParam.put("I_JSRQ", endDate);
        fsdpParam.put("I_GXLX", relationTypeSearch);
        fsdpParam.put("I_SERCH", searchKey);
        String result = fsdpUtilService.requestFsdp(fsdpParam, Const.FSDP_C_NEW_STOCK_LISTED);
        JSONArray jsonArray = JSONObject.parseArray(result);

        List<ListedSharestockInfo> items = Lists.newArrayList();
        jsonArray.forEach( json -> {
            JSONObject jsonObj = (JSONObject) json;
            ListedSharestockInfo listedSharestockInfo=new ListedSharestockInfo();
            listedSharestockInfo.setCustomerId(jsonObj.getString("KHH"));
            listedSharestockInfo.setCustomerName(jsonObj.getString("KHXM"));
            listedSharestockInfo.setPhone(jsonObj.getString("SJHM"));
            listedSharestockInfo.setSecurityName(jsonObj.getString("ZQMC"));
            listedSharestockInfo.setSecurityCode(jsonObj.getString("ZQDM"));
            listedSharestockInfo.setListedDate(jsonObj.getString("SSRQ"));
            listedSharestockInfo.setWinCount(jsonObj.getIntValue("ZQSL"));
            listedSharestockInfo.setAmount(jsonObj.getDoubleValue("CJJE"));
            listedSharestockInfo.setWinDate(jsonObj.getString("ZQRQ"));
            listedSharestockInfo.setAccountType(jsonObj.getString("ZHLX"));
            listedSharestockInfo.setRelationType(jsonObj.getString("GXLX"));

            items.add(listedSharestockInfo);
        });

        return ResponseEntity.ok(new ApiResponseListedSharestock().data(new ApiResponseListedSharestockData().items(items)));
    }
}
